package com.baiyu.common.utils.word;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @PackageName:com.baiyu.education.common.utils.word
 * @ClassName:WordUtil
 * @Description:TODO
 * @Author:王鹏辉
 * @Date:2020/5/13 17:45
 * @Version:1.0
 */
public class WordUtil {
    /**
     * 替换段落中和表格中的指定文字
     */
    public void replaceParagraphValue(XWPFDocument xdoc, Map<String, String> paramMap) throws Exception {
        //替换段落中的指定文字
        Iterator<XWPFParagraph> itPara = xdoc.getParagraphsIterator();
        while (itPara.hasNext()) {
            XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
            Set<String> set = paramMap.keySet();
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                List<XWPFRun> run=paragraph.getRuns();
                for(int i=0;i<run.size();i++)
                {
                    if(run.get(i).getText(run.get(i).getTextPosition())!=null &&
                            run.get(i).getText(run.get(i).getTextPosition()).equals(key))
                    {
                        /**
                         * 参数0表示生成的文字是要从哪一个地方开始放置,设置文字从位置0开始
                         * 就可以把原来的文字全部替换掉了
                         */
                        run.get(i).setText(paramMap.get(key),0);
                    }
                }
            }
        }

        //替换表格中的指定文字
        Iterator<XWPFTable> itTable = xdoc.getTablesIterator();
        while (itTable.hasNext()) {
            XWPFTable table = (XWPFTable) itTable.next();
            int count = table.getNumberOfRows();
            String str = null;
            for (int i = 0; i < count; i++) {
                XWPFTableRow row = table.getRow(i);
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    for (Map.Entry<String, String> e : paramMap.entrySet()) {
                        str = cell.getText();
                        if (cell.getText().equals(e.getKey())) {
                            cell.removeParagraph(0);
                            cell.setText(e.getValue());
                        }else if (str.indexOf("${checkmsg}")!=-1){
                            if ("${checkmsg}".equals(e.getKey())){
                                cell.removeParagraph(0);
                                cell.setText(e.getValue());
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 目前这里是指定参数下次建议可以用不固定
     *
     * @param doc
     * @param key   替换位置
     * @param obj   数据内容
     * @param title 表头
     * @throws IOException
     */
    public void PersonListFor(XWPFDocument doc, String key, Object obj, List title) throws IOException {
        if (!"在研".equals(obj)) {
            List<List<String>> resultList = (List<List<String>>) obj;
            this.exportBg(doc, key, resultList, title);
        } else {
            this.exportBg(doc, key, null, title);
        }
    }

    /**
     * @param doc
     * @param key   替换位置
     * @param list  数据内容
     * @param title 表头
     * @throws IOException
     */
    public void exportBg(XWPFDocument doc, String key, List<List<String>> list, List title) throws IOException {
        List<XWPFParagraph> paragraphList = doc.getParagraphs();
        if (paragraphList != null && paragraphList.size() > 0) {
            Loab:
            for (XWPFParagraph paragraph : paragraphList) {
                List<XWPFRun> runs = paragraph.getRuns();
                for (int i = 0; i < runs.size(); i++) {
                    String text = runs.get(i).getText(0).trim();
                    if (text != null) {
                        if (text.indexOf(key) >= 0) {
                            runs.get(i).setText(text.replace(key, ""), 0);
                            XmlCursor cursor = paragraph.getCTP().newCursor();
                            // 在指定游标位置插入表格
                            XWPFTable table = doc.insertNewTbl(cursor);
                            this.inserInfo(table, list, title);
                            break Loab;
                        }
                    }
                }
            }
        }
    }

    /**
     * 不为空则把信息插入表格
     * 否则新建表格
     *
     * @param table
     * @param list
     * @param title
     */
    private void inserInfo(XWPFTable table, List<List<String>> list, List title) {
        int wid = 9000;
        XWPFTableRow row = table.getRow(0);
        if (list != null) {
            for (int col = 1; col < list.get(0).size(); col++) {//默认会创建一列，即从第2列开始
                // 第一行创建了多少列，后续增加的行自动增加列
                CTTcPr cPr = row.createCell().getCTTc().addNewTcPr();
                CTTblWidth width = cPr.addNewTcW();
                width.setW(BigInteger.valueOf(wid / list.get(0).size()));
            }
            CTTcPr cPr = row.getCell(0).getCTTc().addNewTcPr();
            CTTblWidth width = cPr.addNewTcW();
            width.setW(BigInteger.valueOf(wid / list.get(0).size()));
            for (int i = 0; i < title.size(); i++) {
                XWPFTableCell cell = row.getCell(i);
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                XWPFParagraph newPara = paragraphs.get(0);
                XWPFRun imageCellRunn = newPara.createRun();
                imageCellRunn.setText(title.get(i).toString());
                imageCellRunn.setBold(true);
            }
            for (int i = 0; i < list.size(); i++) {
                row = table.createRow();
                for (int j = 0; j < list.get(i).size(); j++) {
                    CTTc cttc = table.getRow(i).getCell(j).getCTTc();
//                    cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
                    row.getCell(j).getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(wid / list.get(0).size()));
                    row.getCell(j).setText(list.get(i).get(j));
                }
            }
            //最后一行居中
            for (int i = 0; i < list.get(list.size() - 1).size(); i++) {
                CTTc cttc = table.getRow(list.size()).getCell(i).getCTTc();
//                cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
            }
        } else {
            for (int col = 1; col < title.size(); col++) {//默认会创建一列，即从第2列开始
                // 第一行创建了多少列，后续增加的行自动增加列
                CTTcPr cPr = row.createCell().getCTTc().addNewTcPr();
                CTTblWidth width = cPr.addNewTcW();
                width.setW(BigInteger.valueOf(wid / title.size()));
            }
            CTTcPr cPr = row.getCell(0).getCTTc().addNewTcPr();
            CTTblWidth width = cPr.addNewTcW();
            width.setW(BigInteger.valueOf(wid / title.size()));
            for (int i = 0; i < title.size(); i++) {
                XWPFTableCell cell = row.getCell(i);
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                XWPFParagraph newPara = paragraphs.get(0);
                XWPFRun imageCellRunn = newPara.createRun();
                imageCellRunn.setText(title.get(i).toString());
                imageCellRunn.setBold(true);
            }
            row = table.createRow();
            for (int i = 0; i < title.size(); i++) {
                CTTc cttc = table.getRow(0).getCell(i).getCTTc();
                CTTcPr ctPr = cttc.addNewTcPr();
                ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
//                cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
                row.getCell(i).getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(wid / title.size()));
            }
        }

    }
}
